package com.sctvcloud.longchang.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.TitlePagerChangeListener;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.GroupOrderHelperSingled;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.application.Constances;
import com.sctvcloud.longchang.beans.EncyclopediaVo;
import com.sctvcloud.longchang.beans.FCityItem;
import com.sctvcloud.longchang.beans.FCityState;
import com.sctvcloud.longchang.beans.FocusColumn;
import com.sctvcloud.longchang.beans.HomeListItem;
import com.sctvcloud.longchang.beans.NewsClickCountBean;
import com.sctvcloud.longchang.beans.NewsIdBean;
import com.sctvcloud.longchang.beans.NewsItem;
import com.sctvcloud.longchang.beans.NewsListClickRequestBean;
import com.sctvcloud.longchang.beans.NewsListClickVo;
import com.sctvcloud.longchang.http.AbsListNetCallback;
import com.sctvcloud.longchang.http.AbsNetCallBack;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.ui.adapter.CultureTravelAdapter;
import com.sctvcloud.longchang.ui.adapter.EncyclopediaPagerAdapter;
import com.sctvcloud.longchang.ui.adapter.holder.BannerHolder;
import com.sctvcloud.longchang.ui.util.IListShowData;
import com.sctvcloud.longchang.ui.utils.GlideUtil;
import com.sctvcloud.longchang.ui.utils.SkipUtil;
import com.sctvcloud.longchang.utils.ListTypeUtils;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 百科栏目模板
 */
public class EncyclopediaFragment extends ColumnBaseFragment implements OnTabSelectListener {
    @BindView(R.id.banner_layout)
    protected RelativeLayout bannerLayot;
    @BindView(R.id.news_convenientBanner)
    protected ConvenientBanner banner;
    @BindView(R.id.iv_banner)
    protected CustomEXImageView ivPic;
    @BindView(R.id.title_bg)
    protected ImageView titleBg;
    @BindView(R.id.left_title)
    protected TextView leftTitle;
    @BindView(R.id.tv_banner_title)
    protected CustomFontTextView tvTitle;

    @BindView(R.id.baike_tablay)
    protected SlidingTabLayout baikeTablay;
    @BindView(R.id.baike_content_vp)
    protected ViewPager baikeContentVp;

    private EncyclopediaPagerAdapter adapter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getChannelList();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_encyclopedia, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);

    }

    /**
     * 获取模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            return;
        }
        NetUtils.getNetAdapter().getEncyclopediaList(getOwnerName(), channelUrl, new AbsNetCallBack<FCityItem>(FCityItem.class) {
            @Override
            public void onSuc(FCityItem vo) {
                if (null != vo) {
                    getBannerArray(vo.getInstitutionDynamicList());
                    initTab(vo.getInstitutionList());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }


        });
    }


    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @return
     */
    private void getBannerArray(String url) {
        if (TextUtils.isEmpty(url)) {
            bannerLayot.setVisibility(View.GONE);
            return;
        }

        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    initBannerData(newsItems);
                    bannerLayot.setVisibility(View.VISIBLE);
                }else{
                    bannerLayot.setVisibility(View.GONE);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();

            }
        });
    }

    /**
     * 加载banner数据
     *
     * @param newsItems
     */
    private void initBannerData(final List<NewsItem> newsItems) {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = width * 9 / 16;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = width;
        params.height = height;
        banner.setLayoutParams(params);
        banner.setIs169(true);
        banner.setBottomWhite(getContext().getResources().getColor(R.color.no_white));
        banner.setBottomBg(R.mipmap.banner_bottom_bg, true);
        if (newsItems.size() == 1) {
            banner.setVisibility(View.GONE);
            ivPic.setVisibility(View.VISIBLE);
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(newsItems.get(0).getNewsTitle());
            GlideUtil.getGlideWithMid169DefNoFit(getContext(), newsItems.get(0).getNewsImage()).centerCrop().into(ivPic);
            ivPic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBannerItemClick(newsItems.get(0));
                }
            });
            leftTitle.setVisibility(View.GONE);
//                leftTitle.setText("预告");
            titleBg.setVisibility(View.VISIBLE);
        } else {
            leftTitle.setVisibility(View.GONE);
            titleBg.setVisibility(View.GONE);
            banner.setVisibility(View.VISIBLE);
            tvTitle.setVisibility(View.GONE);
            ivPic.setVisibility(View.GONE);
//                flowView.setPages(newsItems, new MZHolderCreator() {
//                    @Override
//                    public MZViewHolder createViewHolder() {
//                        return new MzBannerHolder(newsItems.size());
//                    }
//                });
//                JLog.e("aaa will call flow start");
//                flowView.start();
            banner.setTitlePagerChangeListener(new TitlePagerChangeListener<NewsItem>() {
                @Override
                public void onTitlePagetChange(TextView title, int postiton, NewsItem data) {
                    if (data != null && !TextUtils.isEmpty(data.getDataTitle())) {
                        title.setVisibility(View.VISIBLE);
                        title.setText(data.getDataTitle());
                    }
                }

                @Override
                public void onTitlePagetChange(TextView leftTitle, TextView title, int postiton, NewsItem data) {

                }
            });
            banner.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    return new BannerHolder();
                }
            }, newsItems)
                    //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                    .setPageIndicator(new int[]{R.mipmap.banner_icon_normal, R.mipmap.banner_icon_down})
                    //设置指示器的方向
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
            banner.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    NewsItem channelBean = newsItems.get(position);
                    onBannerItemClick(channelBean);
                }
            });
            if (!banner.isTurning()) {
                banner.startTurning(3000);
            }


        }

    }

    private void initTab(List<FCityState> institutionList) {
        if (ListUtils.isListValued(institutionList)) {
            if (adapter == null) {
                adapter = new EncyclopediaPagerAdapter(getContext(), getChildFragmentManager(), institutionList);
                baikeContentVp.setAdapter(adapter);
                baikeContentVp.setOffscreenPageLimit(1);
                baikeTablay.setViewPager(baikeContentVp);
                baikeTablay.setChangeSize(true);
            } else {
                adapter.setData(institutionList);
            }
            adapter.notifyDataSetChanged();
            baikeTablay.setCurrentTab(0);
            baikeTablay.setTabPaddingPx(getResources().getDimension(R.dimen.tab_home_padding));
            baikeTablay.setOnTabSelectListener(this);
        }
    }

    @Override
    public void onTabSelect(int position) {

    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onTabScrollTo(int position) {

    }

    /**
     * banner点击
     *
     * @param channelBean
     */
    private void onBannerItemClick(NewsItem channelBean) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("位置", "大图推荐"));
        ArrayList<Pair<String, String>> tempPair = new ArrayList<>();
        tempPair.addAll(pairs);
        tempPair.add(new Pair<>("行为类型", "点击"));
        GridsumWebDissector.getInstance().trackEvent(EncyclopediaFragment.this, "", channelBean.getNewsTitle(), "", 200, tempPair);
        HashMap<String, String> map = new HashMap<>();
        for (Pair<String, String> p : pairs) {
            map.put(p.first, p.second);
        }
        if (!SkipUtil.skipWithNewsItem(getContext(), channelBean, map)) {
            Toast.makeText(getContext(), "数据错误", Toast.LENGTH_SHORT).show();
        }

    }

}
